<?php
declare (strict_types = 1);

namespace app\common\model;
use think\facade\Db;

class ExamineAnswer extends Base
{

    protected $name = 'examine_answer';
    /**
     * 提交试卷
     */
    public static function submit($param,$user)
    {
        try {
            $time = time();
            $sttime = $time-60*5;
            $info = ExamineTake::where(['uid' => $user->id,'examine_id'=>$param['id']])->find();
            $find = Examine::where('id',$param['id'])->find();
            if (empty($info)) {
                return ['code' => -1, 'msg' => '暂无考试试卷'];
            }
            if($time<$find['start_time']){
                return ['code'=>-1,'msg'=>'考试还未开始'];
            }
            if($sttime>$find['end_time']){
                return ['code'=>-1,'msg'=>'考试已结束'];
            }
            $data = $param['data'];

            foreach ($data as $key => $value) {
                $type = Exam::where(['id'=>$value['id']])->value('types');
                $parent = parent::where(['uid'=>$user->id,'exam_id'=>$value['id'],'examine_id'=>$find['id']])->find();
                $list=[
                    'uid'=>$user->id,
                    'exam_id'=>$value['id'],
                    'examine_id'=>$find['id'],
                    'answer'=>$value['answer'],
                    'score'=>$type == 1?$info['radio_score']:$info['check_score'],
                    'types'=>self::judge($value['id'],$value['answer']),
                    'paper_time'=>time()
                ];
                if(empty($parent)){
                    parent::create($list);
                }
            }
            $score = parent::where(['uid'=>$user->id,'types'=>1,'examine_id'=>$find['id']])->sum('score');
            if($score>=90){
                $status = 1;
            }else{
                $status = 2;
            }
            $info->score = $score;
            $info->status = $status;
            $info->save();
            return ['code' => 1, 'msg' => '提交成功！'];
        }catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 判断对错
     */
    public static function judge($id,$my_answer)
    {
        $answer = Exam::where(['id'=>$id])->value('answer');
        return $answer==$my_answer?1:2;
    }
}
